package com.mamesoft.namibiamc.ws;

import com.mamesoft.namibiamc.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import hirondelle.date4j.DateTime;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

@Path("/sms")
public class SmsWs {

    @GET
    @Produces(MediaType.APPLICATION_XML)
    @Path("{phone}")
    public String getData(@PathParam("phone") String number, @QueryParam("text") String text) {
        String xml = "";
        String visitcount = "";
        Connection c = null;
        try {
            if (text == null) {
                text = "";
            }
            if (text.toLowerCase().contains("visite") || "".equals(text)) {
                c = JDBC.connect();
                String q = "SELECT id FROM paziente WHERE telefono='" + number + "'";
                ResultSet set = JDBC.executeQuery(q, c);
                boolean isValidPhone = set.next();
                if (isValidPhone) {
                    q = "SELECT username, data, tipo_visita, descrizione "
                            + "FROM paziente "
                            + "JOIN cartella ON paziente.id = pid "
                            + "WHERE telefono =  '" + number + "' "
                            + "AND richiami >0 "
                            + "AND is_fatta =  'F'";
                    int count = 0;
                    set = JDBC.executeQuery(q, c);
                    while (set.next()) {
                        count++;
                        xml += "<visita>";
                        xml += "<username>" + set.getString("username") + "</username>";
                        Timestamp t = set.getTimestamp("data");
                        DateTime d = new DateTime(t.toString());
                        xml += "<data-visita>" + d.format("DD/MM/YYYY hh:mm") + "</data-visita>";
                        xml += "<tipo-visita>" + set.getString("tipo_visita") + "</tipo-visita>";
                        xml += "<descrizione>" + set.getString("descrizione") + "</descrizione>";
                        xml += "</visita>";
                    }
                    visitcount += "<num-visite>" + count + "</num-visite>";
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(SmsWs.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            if (c != null) {
                try {
                    c.close();
                } catch (SQLException ex) {
                    Logger.getLogger(SmsWs.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        xml += "</visite>";
        return "<visite>" + visitcount + xml;
    }
}
